import {Injectable} from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class PrintService {

    constructor() {
    }

    printNode(node: Node) {
        if (!node) {
            return;
        }

        const style = this._getStyle();
        const container = this._getContainer();

        const parent = node.parentNode;
        const next = node.nextSibling;
        container.appendChild(node);
        document.body.appendChild(style);
        document.body.appendChild(container);

        window.print();

        parent.insertBefore(node, next);
        document.body.removeChild(container);
        document.body.removeChild(style);
    }

    printHtml(html) {
        if (!html) {
            return;
        }

        const style = this._getStyle();
        const container = this._getContainer();

        container.innerHTML = html;
        document.body.appendChild(style);
        document.body.appendChild(container);

        this._getLoadPromise(container).then(() => {
            window.print();

            document.body.removeChild(style);
            document.body.removeChild(container);
        });
    }

    // 设置打印样式
    private _getStyle() {
        const style = document.createElement("style");
        //body.height: auto, 否则只会打印一页
        style.innerHTML = `
            #print-container {
                display: none;
            }
            @media print {
                @page {
                    margin: 0;
                }
                body > :not(#print-container) {
                    display: none;
                }
                html,body {
                    display: block !important;
                    height: auto !important;
                }
                #print-container {
                    display: block;
                }
                .print-page-break{
                    page-break-after: always;
                }
            }`;

        return style;
    }

    // 新建打印DOM，用于放置打印内容
    private _getContainer() {
        const element = document.getElementById('print-container');
        if (element) document.body.removeChild(element);
        const container = document.createElement("div");
        container.setAttribute("id", "print-container");
        return container;
    }

    // 图片完全加载后再调用打印方法
    private _getLoadPromise(dom) {
        const imgs = [].slice.call(dom.querySelectorAll("img"));

        if (imgs.length === 0) {
            return Promise.resolve();
        }

        let count = 0;
        return new Promise(resolve => {
            function check() {
                count++;
                if (count === imgs.length) {
                    resolve(true);
                }
            }

            imgs.forEach(img => {
                img.addEventListener("load", check);
                img.addEventListener("error", check);
            })
        });
    }
}
